package JavaCore.base;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Lambda表达式的十种用法
 * 
 * @author Administrator
 *
 */
public class LambdaDemo {

	public static void main(String[] args) {
		List<String> list = Arrays.asList("apple", "orange", "banana");
		// 1.循环
		for (String string : list) {
			System.out.println(string);
		}
		list.forEach(System.out::println);
		list.forEach(s -> System.out.println(s));
		list.forEach(s -> {
			System.out.println(s);
		});

		// 2.排序:根据首字母排序
		// Collections.sort(list, new Comparator<String>() {
//			@Override
//			public int compare(String o1, String o2) {
//				return o1.compareTo(o2);
//			}
//		});
		System.out.println("排序==》" + list);
		Collections.sort(list, (a, b) -> {
			return a.compareTo(b);
		});
		System.out.println("排序==》" + list);

		// 3.过滤：只要开头是o的字符串
		List<String> list2 = new ArrayList<>();
		for (String s : list) {
			if (s.startsWith("o")) {
				list2.add(s);
			}
		}
		System.out.println(list2);
		List<String> list3 = list.stream().filter(s -> s.startsWith("o")).collect(Collectors.toList());
		System.out.println(list3);

		// 4.映射:过滤出首字母带a的单词并转化成大写后放到集合中
		List<String> list4 = list.stream().filter(s -> s.startsWith("a")).map(s -> s.toUpperCase())
				.collect(Collectors.toList());
		System.out.println(list4);

		// 5.规约：集合的数字累加
		List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5);
		int sum = 0;
		for (Integer i : intList) {
			sum += i;
		}
		System.out.println(sum);

		int sum2 = intList.stream().reduce(0, (a, b) -> {
			return a + b;
		});
		System.out.println(sum2);

		// 6.分组
		// Collectors.groupingBy(null)



		// 7.函数式接口的调用
		MyInterFace myInterFace = new MyInterFace() {
			@Override
			public String doSomething(String s) {
				return s + "你好";
			}
		};
		System.out.println(myInterFace.doSomething("小明"));

		MyInterFace myInterFace2 = (s) -> {
			return s + "你好";
		};
		System.out.println(myInterFace2.doSomething("小刚"));

		// 8.进行线程创建
		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				System.out.println("Hello");

			}
		});
		thread.start();

		thread = new Thread(() -> {
			System.out.println("Hello");
		});
		thread.start();

		// 9.进行Optional操作:如果一个字符串不是null则把他转化成大写输出，否则就输出NULL
		String a = "apple";
		String b = Optional.ofNullable(a).map(s -> s.toUpperCase()).orElse("NULL");
		System.out.println(b);

		// 10.进行Stream流操作
	}

}

interface MyInterFace {
	public String doSomething(String s);
}
